<?php
/**
 * Created by PhpStorm.
 * User: xudongsheng
 * Date: 2017/9/17
 * Time: 上午1:19
 */

namespace app\admin\model;


class File extends \think\Model
{
    /** 自动写入 时间
     * @var bool
     */
    protected $autoWriteTimestamp   =   true;
    /** 上传 保存对象 object  OR  array
     * @var null
     */
    protected $file     =   null;
    /** 上传文件 验证 规则  3种  大小  后缀  mime类型
     * @var array
     */
    protected $rules    =   [
                'img'   =>   [
                    'ext'   =>  [
                        'jpg'   =>  'image/jpg',
                        'jpeg'  =>  'image/jpeg',
                        'png'   =>  'image/png',
                    ],
                    'size'  =>  1024*1024*1024*2,
                ],
                'flash' =>  [
                    'ext'   =>  [
                        'swf'   =>  'application/x-shockwave-flash'
                    ],
                    'size'  =>  1024*1024*1024*2,
                ],
    ];
    /** 默认 上传文件 存储类型
     * @var string
     */
    protected $type     =   'img';
    /** 错误消息
     * @var string
     */
    protected $error    =   '';
    /** 保存 文件 路径  未来 保存到配置 中
     * @var string
     */
    protected $path     = './static/Uploads';  // 存在 配置文件中

    /** 上传处理
     * @param string $type
     * @param null $scene
     * @return array|mixed
     */
    public function uploads($type = 'img',$key = ''){
        //文件上传
        $this->file = $this->file?:request()->file($key);
        $this->type =   $type?:'img';
        $info   =   [];
        if (!$this->file instanceof \think\File){
            foreach ($this->file as $k=>$v){
               if ( $this->ruleCheck($v) AND (($file = $this->isExistence($v)) OR ($file = $this->move($v)))){
                    $info[][$k]   =   ['error'=>false,'data'=>$this->getFileInfo($file)] ;
               }else{
                    $info[][$k]   =   ['error'=>true,'msg'=>$this->error];
               }
            }
            return count($info) > 1?$info:$info[0];
        }
        if ( $this->ruleCheck($this->file) AND (($file = $this->isExistence()) OR ($file = $this->move()))){
            return ['error'=>false,'data'=>$this->getFileInfo()];
        }
        return ['error'=>true,'msg'=>$this->error];
    }


    /** 检查文件 是否已经上传
     * @param null $file
     * @return bool
     */
    protected function isExistence($file = NULL){
        $file   =   $file?:$this->file;
        return self::where(['md5'   =>  $file->hash('md5')])->field('file_name,save_path,type,size,name,md5,mime')->find()?:false;
    }

    /** 获取 文件信息
     * @param null $file
     * @return array
     */
    protected function getFileInfo($file = NULL){
        $file   =   $file?:$this->file;
        $tmp    =   [];
        // 保存路径
        if ($file instanceof \think\Model){
            return $file->toArray();
        }
        $tmp['mime']        =   $file->getMime();
        $tmp['md5']         =   $file->hash('md5');
        $tmp['name']        =   $file->getInfo('name');
        $tmp['size']        =   $file->getInfo('size');
        $tmp['type']        =   $this->type;
        $tmp['save_path']   =   formatLink($this->getSavePath().'/'.$file->getSaveName());
        $tmp['file_name']   =   $file->getFilename();

        // 存入 数据库
        self::create($tmp);
        return  $tmp;
    }

    /** 移动文件
     * @param null $file
     * @return bool
     */
    protected function move($file = NULL){
        $file   =   $file?:$this->file;
//        if (!$this->ruleCheck($file))return false;
        if (!($newFile = $file->move($this->getSavePath()))){
            $this->error($file->getError());
            return false;
        }
        return $newFile;
    }

    /** 获取 保存 路径
     * @return string
     */
    protected function getSavePath(){
        if ((substr($this->path,0,1) !== '/') AND (substr($this->path,0,1) !== '.')){
            $this->path = './'.$this->path;
        }
        if (strpos($this->path,'/') === 0){
            $this->path =   '.'.$this->path;
        }
        return $this->path.'/'.$this->type;
    }

    /** 设置 规则
     * @param $file
     * @return bool
     */
    protected function ruleCheck($file){
       if (!isset($this->rules[$this->type]) OR !($rule = $this->rules[$this->type])){
            $this->error('此文件不是能够上传的文件类型！');
            return false;
       }
       $ext = [];
       $mime= [];
        foreach ($rule['ext'] as $s => $m){
            $ext[]  =   $s;
            $mime[] =   $m;
        }
        $validate   =   [
            'size'  =>  isset($rule['size'])?$rule['size']:0,
            'ext'   =>  implode(',',$ext),
            'type'  =>  implode(',',$mime)
        ];
        return $file->validate($validate);
    }

    /** 设置 错误消息
     * @param $msg
     */
    protected function error($msg){
        $this->error = $msg;
    }

    public function getCreateTimeAttr($value){
        return date('Y-m-d H:i:s',$value);
    }


}